import socket
import json
import struct
import os

sk = socket.socket()
sk.connect(('127.0.0.1', 9000))


def my_send(dic, encoding='utf-8'):
    str_dic = json.dumps(dic)
    bdic = str_dic.encode(encoding)
    len_dic = len(bdic)
    msg_len = struct.pack('i', len_dic)
    sk.send(msg_len)
    sk.send(bdic)


#登录
username = input('username>>>')
password = input('password>>>')
dic = {'operate': 'login', 'username': username, 'password':password}
my_send(dic)

#接收登录结果的字典
msg_len = sk.recv(4)
msg_len = struct.unpack('i', msg_len)[0]
str_dic = sk.recv(msg_len).decode('utf-8')
dic = json.loads(str_dic)

if dic['operate'] == 'login' and dic['flag']:
    print('登录成功')
else:
    print('fail')

#选择功能 upload
if dic['result']:
    filepath = input('请输入路径:').strip()
    if os.path.isfile(filepath):
        filename = os.path.basename(filepath) #返回path最后的文件名
        filesize = os.path.getsize(filepath)
        dic = {'operate': 'upload', 'filename': filename, 'filesize': filesize}
        my_send(dic)



sk.close()